package com.itheima.servlet;

import com.itheima.domain.User;
import com.itheima.service.Service;
import com.itheima.service.impl.ServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        //获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        /*System.out.println(username);
        System.out.println(password);*/
        Service service = new ServiceImpl();
        User user = service.login(username, password);
        System.out.println("hello");

        //虚拟路径contextPath
        /*String contextPath = req.getContextPath();
        System.out.println(contextPath);*/

        if(user == null){
            //resp.getWriter().write("登录失败");
            System.out.println("登录失败");
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else{
            //登录成功,保存客户数据
            HttpSession session = req.getSession();
            session.setAttribute("user",user);

            String choice = req.getParameter("choice");
            Cookie cookieName = new Cookie("username", user.getUsername());
            Cookie cookiePsd = new Cookie("password", user.getPassword());

            //设置cookie路径
            cookieName.setPath("/");
            cookiePsd.setPath("/");
            if("1".equals(choice)){
                cookieName.setMaxAge(7*24*3600);//保留7天
                cookiePsd.setMaxAge(7*24*3600);//保留7天
            }else{
                cookieName.setMaxAge(0);//不保留
                cookiePsd.setMaxAge(0);//不保留
            }
            resp.addCookie(cookieName);
            resp.addCookie(cookiePsd);
            resp.sendRedirect(req.getContextPath()+"/success.jsp");
        }

    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}
